<template>
  <div class="content-wrapper">
    <!-- <div class="content-header">
      <el-breadcrumb
        style="margin-top: 10px"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          v-for="(item, index) of brandList"
          :key="index"
          @click.native="breadsClick(item)"
        >
          <span
            v-if="index == 0"
            style="cursor: pointer"
            @click.stop="doThis"
            @click="backtrack(index)"
            >{{ repositoryName }} <i class="el-icon-arrow-right classi" />
          </span>
          <span style="cursor: pointer">{{ item.name }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div> -->
    <!-- <div class="content-container"> -->
      <el-form ref="listQuery" :inline="true" class="filter-container">
        <el-form-item label="文件等级">
          <el-select
            v-model="listQuery.documentLevel"
            clearable
            size="mini"
            @change="handleLevelChange"
          >
            <el-option
              v-for="documentLevel in levels"
              :key="documentLevel.value"
              :label="documentLevel.label"
              :value="documentLevel.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件属性">
          <el-select v-model="listQuery.documentProperty" clearable size="mini">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="文件编号" min-width="220">
          <el-input
            v-model.trim="listQuery.documentCode"
            type="text"
            size="mini"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button
            class="filter-item"
            size="small"
            round
            type="primary"
            icon="el-icon-search"
            @click="getDataList"
          >
            搜索
          </el-button>
        </el-form-item>
        <!-- <el-form-item>
          <el-button
            size="small"
            round
            class="filter-item"
            @click="batchDownload"
          >批量下载(限时)</el-button>
        </el-form-item> -->
      </el-form>

      <div class="filter-container" />
      <el-scrollbar>
        <div>
          <!--  v-loading="listLoading" -->
          <el-table
            height="700"
            :data="
              list.filter(
                (data) =>
                  !searchName ||
                  data.documentCode
                    .toLowerCase()
                    .includes(searchName.toLowerCase())
              )
            "
            highlight-current-row
            style="width: 100%; overflow: scroll"
            :row-class-name="tableRowClassName"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="index" width="50" />

            <!-- <el-table-column type="selection" width="55" fixed /> --> 
            <el-table-column
              label="文件编号"
              min-width="170"
              prop="documentCode"
            >
              <template slot="header" slot-scope="scope">
                <el-input
                  v-model="searchName"
                  size="mini"
                  placeholder="输入文件编号搜索"
                />
              </template>
              <template slot-scope="scope">
                <i v-if="scope.row.flowType === 4" class="el-icon-download" />
                <span style="margin-left: 10px">{{
                  scope.row.documentCode
                }}</span>
              </template>
            </el-table-column>

            <el-table-column
              label="文件名称"
              min-width="200px"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span
                  v-if="scope.row.folderName"
                  style="cursor: pointer"
                  @click="childFile(scope.row)"
                >
                  <svg class="icon" aria-hidden="true">
                    <use
                      :xlink:href="iconType(scope.row.fileExtension).class"
                    />
                  </svg>
                  {{ scope.row.folderName }}</span
                >
                <span
                  v-if="scope.row.documentName"
                  style="cursor: pointer"
                  @click="updateDocument(scope.row)"
                  ><svg class="icon" aria-hidden="true">
                    <use
                      :xlink:href="iconType(scope.row.fileExtension).class"
                    /></svg
                  >{{ scope.row.documentName }}{{ scope.row.fileExtension }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="文件等级"
              prop="documentLevel"
              width="150px"
            >
              <template slot-scope="{ row }">
                {{ formatByKeyValue(flowOptions, row.documentLevel) }}
              </template>
            </el-table-column>
            <el-table-column
              label="文件属性"
              prop="documentProperty"
              width="100px"
            >
              <template slot-scope="{ row }">
                {{ formatByKeyValue(flowOptions, row.documentProperty) }}
              </template>
            </el-table-column>
            <el-table-column
              label="文件版本"
              align="center"
              width="100px"
              prop="documentVersion"
            >
              <template slot="header">
                <span @click="rule_breaking">文件版本</span>
              </template>
            </el-table-column>
            <el-table-column label="生效时间" prop="effectDate" width="150px" />
            <el-table-column
              label="操作"
              align="center"
              width="200"
              fixed="right"
            >
              <template v-if="row.documentCode" slot-scope="{ row }">
                <el-dropdown trigger="click" class="filter-item">
                  <el-button type="text"><i class="el-icon-more" /></el-button>
                  <el-dropdown-menu slot="dropdown" class="user-dropdown">
                    <el-dropdown-item @click.native="checkInformation(row)"
                      >查看</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="row.flowType === 4"
                      @click.native="fileDownload(row)"
                      >下载</el-dropdown-item
                    >
                    <!-- <el-dropdown-item
                      v-if="isRecord(row)"
                      @click.native="openCreateRecordDialog(row)"
                      >新增记录</el-dropdown-item
                    > -->
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          <dir class="but">共{{ list.length }}条</dir>
        </div>
      </el-scrollbar>
    <!-- </div> -->
    <Information :information-data="informationData" />
  </div>
</template>

<script>
import {
  saveFolder,
  deleteFolder,
  listTreeFolderOnlyFolder
} from '@/api/fd/folder'
import { unity } from '@/styles/js/setIconType.js'
import { getRelease } from '@/api/xd/documentFlow'
import { listDictTreeItem } from '@/api/base/dict'
import { releaseOftenUse, downloadFile } from '@/api/fd/document.js'
import { listTeamTree } from '@/api/fd/repository'
import permissionList from '@/utils/permissionList'
import { copy } from '@/api/fd/document'
import Information from '@/views/active/document_release_list/components/Information/index.vue'
import { getFlowOptions } from '@/views/flow/js/dictionary.js'
import { fileDownload } from '@/utils/redo_download.js'
import { formatByKeyValue } from '@/utils'

export default {
  components: {
    File,
    Information
  },
  data() {
    return {
      iconType: unity.setIconType,
      documentName: null,
      multipleSelection: [],
      list: [],
      total: 0,
      listLoading: true,
      temp: {
        parentFolderId: null,
        folderName: null,
        folderId: null,
        repositoryId: null
      },
      brandList: [],
      brands: [],
      repositoryName: '现行文件',
      dialogVisible: false,
      data: [],
      listQuery: {},
      flowTypeOptions: [],
      levels: [],
      categories: [],
      searchData: {},
      switchData: '',
      recordVisible: false, // 新增记录对话框
      recordData: {
        documentId: '',
        documentName: ''
      },
      treeProps: {
        children: 'children',
        label: 'label',
        id: 'value'
      },
      treeData: [],
      options: [],
      teamAndRepository: [],
      informationData: {},
      n: 0,
      ruleBreaking: false,
      flowOptions: null,
      searchName: ''
    }
  },
  watch: {
    $route() {
      this.$router.go(0)
    }
  },
  async mounted() {
    fileDownload
    this.flowOptions = Array.from(await getFlowOptions())
    console.log(  this.flowOptions,'  this.flowOptions');
    this.getList()
    this.getBread()
    this.loadLevelOptions()
  },
  methods: {
    formatByKeyValue,
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    },
    createRecord() {
      console.log(this.recordData, 'this.recordData')
      copy(this.recordData).then((res) => {
        this.recordVisible = false
        window.open(
          'onlyoffice/createDocument.html?&token=' +
            this.$store.getters.token +
            '&documentId=' +
            res.data.documentId +
            '&mode=edit' +
            '&urldata=' +
            process.env.VUE_APP_BASE_API
        )
      })
    },
    /**
     * 选择文件夹时触发
     */
    handleCheckChange(data, checkbox, node) {
      if (checkbox === true) {
        this.recordData.destFolderId = data.value
        this.$refs.treeForm.setCheckedNodes([data])
      }
    },
    /**
     * 知识库发生改变时触发
     */
    handleChange(row) {
      this.recordData.destRepositoryId = row[row.length - 1]
      listTreeFolderOnlyFolder({ repositoryId: row[row.length - 1] }).then(
        (res) => {
          this.treeData = res.data.data
          // this.getItem(this.treeData)
        }
      )
    },
    recordClose() {
      // 新增记录对话框关闭时
      this.recordData = {
        documentId: '',
        documentName: ''
      }
      this.treeData = []
    },
    openCreateRecordDialog(row) {
      this.recordVisible = true
      this.recordData.documentId = row.documentId
      const date = this.dateFormat('YYYY-mm-dd HH:MM', new Date())
      this.recordData.documentName = '记录文件' + date
      if (!this.options || this.options.length == 0) {
        listTeamTree({
          permission: permissionList.VISIBLE + permissionList.NEW
        }).then((res) => {
          res.data.map((item) => {
            if (!item.children) {
              item.disabled = true
            }
          })
          this.options = res.data
        })
      }
    },
    /**
     * 判断是为可新增记录文件
     * @param row
     */
    isRecord(row) {
      if (row.documentCode.split('-')[2] == 'JL') {
        return true
      }
      return false
    },
    // 返回上一页
    // goBack() {
    //   this.$router.go(-1)
    // },
    // 返回
    backtrack(index) {
      console.log(index, 'index')
      this.temp.parentFolderId = ''
      this.getList()
      this.getBread()
    },
    breadsClick(item, index) {
      this.breads = JSON.parse(localStorage.getItem('breadList'))
      var flag = true
      for (var i = this.breads.length - 1; i >= 0; i--) {
        if (this.breads[i].parentFolderId === item.parentFolderId) {
          flag = false
        }
        if (flag) {
          this.breads.splice(i, 1)
        }
      }
      localStorage.setItem('breadList', JSON.stringify(this.breads))
      this.temp.parentFolderId = item.parentFolderId
      this.getList()
      this.getBread()
    },
    getBread() {
      var breads = localStorage.getItem('breadList')
      if (breads !== 'undefined') {
        this.brandList = JSON.parse(breads)
      } else {
        localStorage.setItem('breadList', '[]')
      }
      if (!this.temp.parentFolderId) {
        this.brandList = []
        localStorage.setItem('breadList', '[]')
      }
    },
    oneDeleteFolder(row) {
      deleteFolder({ folderId: row.folderId }).then((res) => {
        this.$message.success('删除成功')
        this.getList()
      })
    },
    createDocument(val) {
      this.$prompt('请输入文档名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          var data = {
            documentType: val,
            folderId: this.temp.parentFolderId ? this.temp.parentFolderId : 0,
            repositoryId: this.temp.repositoryId,
            documentName: value
          }
          createDocument(data).then((res) => {
            if (res.data != null) {
              this.getList()
              window.open(
                'onlyoffice/createDocument.html?&token=' +
                  this.$store.getters.token +
                  '&documentId=' +
                  res.data.documentId +
                  '&mode=edit' +
                  '&urldata=' +
                  process.env.VUE_APP_BASE_API
              )
            } else {
              this.$message.error('创建失败')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消创建'
          })
        })
    },
    createFolder() {
      this.$prompt('新建文件夹名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          var data = {
            repositoryId: this.temp.repositoryId,
            parentFolderId: this.temp.parentFolderId
              ? this.temp.parentFolderId
              : 0,
            folderName: value
          }
          saveFolder(data).then((res) => {
            this.$message.success('创建成功')
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消创建'
          })
        })
    },
    childFile(row) {
      console.log(row, 'row')
      var path = {
        name: row.folderName,
        path: '/document/file/' + row.repositoryId,
        parentFolderId: row.folderId
      }
      this.breads = JSON.parse(localStorage.getItem('breadList'))
      this.breads.push(path)
      localStorage.setItem('breadList', JSON.stringify(this.breads))

      this.temp.repositoryId = row.repositoryId
      this.temp.parentFolderId = row.folderId
      this.getList()
      this.getBread()
    },
    updateDocument(row) {
      if (row.fileExtension.indexOf('.pdf') != -1) {
        window.open(
          process.env.VUE_APP_BASE_API +
            '/api/fd/pdf/get_document_by_pdf?documentId=' +
            row.documentId
        )
      } else {
        // 记录文件点击次数
        releaseOftenUse({ documentReleaseId: row.documentReleaseId })
        window.open(
          'onlyoffice/createDocument.html?&token=' +
            this.$store.getters.token +
            '&documentId=' +
            row.documentId +
            '&mode=view' +
            '&urldata=' +
            process.env.VUE_APP_BASE_API
        )
      }
    },
    // handleNewCommand(command) {
    //   window.open('createDocument.html')
    // },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getList() {
      this.temp.repositoryId = this.$route.params.repositoryId
      if (this.$route.query.parentFolderId) {
        this.temp.parentFolderId = this.$route.query.parentFolderId
      }
      getRelease(this.temp).then((res) => {
        console.log(this.temp, 'temp', res)
        this.list = Array.from(res.data) || []
        this.listLoading = false
      })
      if (this.$route.query.repositoryName) {
        this.repositoryName = this.$route.query.repositoryName
      }
    },
    viewDocument(row) {
      window.open(
        'onlyoffice/createDocument.html?&token=' +
          this.$store.getters.token +
          '&documentId=' +
          row.documentId +
          '&mode=edit' +
          '&urldata=' +
          process.env.VUE_APP_BASE_API
      )
    },
    // 分享
    async openShare(row, type) {
      this.saveShare.shareType = type
      if (type == 0) {
        this.saveShare.shareId = row.documentId
      }
      this.dialogVisibles = true
    },
    // 获取文件等级属性
    loadLevelOptions() {
      listDictTreeItem({ dictGroupCode: 'document_category' }).then((res) => {
        this.levels = res.data
      })
    },
    handleLevelChange(val) {
      if (this.listQuery.documentProperty) {
        this.listQuery.documentProperty = ''
      }
      for (let i = 0, len = this.levels.length; i < len; i++) {
        if (this.levels[i].value === val) {
          this.categories = this.levels[i].children
          if (this.listQuery.type) {
            this.listQuery.type = ''
          }
        }
      }
    },
    // 搜索
    getDataList() {
      getRelease(this.listQuery).then((res) => {
        this.list = res.data
        this.listLoading = false
      })
    },
    checkInformation(row) {
      this.informationData = {
        drawer: true,
        row: row
      }
    },
    // 违规操作
    rule_breaking() {
      this.n = this.n + 1
      if (this.n == 3) {
        this.ruleBreaking = true
      }
    },
    checkInformation_ruleBreaking(row) {
      window.open(
        'onlyoffice/createDocument.html?&token=' +
          this.$store.getters.token +
          '&documentId=' +
          row.documentId +
          '&mode=edit' +
          '&urldata=' +
          process.env.VUE_APP_BASE_API
      )
    },
    // 下载功能
    fileDownload(row) {
      downloadFile({
        documentId: row.documentId
      }).then((res) => {
        const { url, documentName } = res.data
        this.getBlob(url).then((blob) => {
          this.saveAs(blob, documentName)
        })
      })
    },
    // 下载重命名
    getBlob(url) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.responseType = 'blob'
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response)
          }
        }
        xhr.send()
      })
    },
    // 下载重命名
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename)
      } else {
        const link = document.createElement('a')
        const body = document.querySelector('body')

        link.href = window.URL.createObjectURL(blob)
        link.download = filename
        link.style.display = 'none'
        body.appendChild(link)
        link.click()
        body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
      }
    },
    // 批量下载
    batchDownload() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请选择下载文件')
      } else {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ;((t, data) => {
            setTimeout(() => {
              this.fileDownload(data)
            }, 1000 * t) // 每秒执行一次
          })(i, this.multipleSelection[i])
        }
      }
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.flowType === 4) {
        return 'success-row'
      } else {
        return ''
      }
    }
  }
}
</script>

<style  scoped>
.content-header {
  padding-bottom: 0px !important;
}
.tub {
  display: none;
}
.but {
  text-align: right;
  padding-right: 20px;
  font-size: 14px;
  color: #909399;
}
/deep/ .el-table .success-row {
  background: #f0f9eb;
}
</style>

